﻿using FastCodeGeneration.Core.Framework;
using FastCodeGeneration.Entity;
using FastCodeGeneration.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FastCodeGeneration.Repository
{
    public class ModuleRepository : BaseRepository<Module>, IModuleRepository
    {

        public IPage<Module> SelectByCondition(Condition condition)
        {
            QueryWrapper<Module> wrapper = this.getQueryWrapperByCondition(condition);
            if (condition.ExportAll)
            {
                condition.PageSize = 10000;
            }
            Page<Module> page = new Page<Module>(condition.PageIndex, condition.PageSize);
            int totalNumber = 0;
            if (wrapper.GetSugarParameters().Count > 0)
            {
                var sql = $"SELECT * FROM (SELECT t.*,p.name as ProjectName FROM sys_module t LEFT JOIN Project p on t.project_id=p.Id) WHERE {wrapper.getSqlResult()}";
                page.Records = Context.SqlQueryable<Module>(sql).AddParameters(wrapper.GetSugarParameters())
                    .ToPageList(page.PageIndex, page.PageSize, ref totalNumber);
            }
            else
            {
                var sql = $"SELECT * FROM (SELECT t.*,p.name as ProjectName FROM sys_module t LEFT JOIN Project p on t.project_id=p.Id)";
                page.Records = Context.SqlQueryable<Module>(sql).ToPageList(page.PageIndex, page.PageSize, ref totalNumber);
            }
            page.TotalCount = totalNumber;
            return page;
        }

        public List<Module> SelectByProjectId(int projectId)
        {
            return Context.Queryable<Module>().Where(e => e.ProjectId == projectId).ToList();
        }

    }
}
